package mil.af.amc.adpetracker.web.helpers;

import mil.af.amc.adpetracker.model.Ros;
import mil.af.amc.adpetracker.service.RosService;
import mil.af.amc.adpetracker.service.ServiceException;
import mil.af.amc.radtaglibrary.tags.PageContextAwareBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.PageContext;
import java.util.Collections;
import java.util.List;

/**
 * ViewHelper for ROS information
 *
 * @author TSgt Jason Ferguson
 */
@Service("rosViewHelper")
public class RosViewHelper implements PageContextAwareBean {

    private static final Log log = LogFactory.getLog(RosViewHelper.class);

    private RosService rosService;

    @Autowired
    public void setRosService(RosService rosService) {
        this.rosService = rosService;
    }

    private PageContext pageContext;

    @Autowired
    public void setPageContext(PageContext pageContext) {
        this.pageContext = pageContext;
    }

    public Ros getRosPackage() {

        ServletRequest request = pageContext.getRequest();
        int rosPackageId = Integer.parseInt(request.getParameter("rosPackageId"));

        return rosService.getById(rosPackageId);

    }

    public List<Ros> getAll() {

        try {

            List<Ros> results = rosService.getAll();
            Collections.sort(results);
            return results;
        } catch (ServiceException e) {
            log.debug("rosViewHelper.getAll() threw ServiceException", e);
            return null;
        }
    }

    public List<Ros> getAllByAccount() {

        ServletRequest request = pageContext.getRequest();
        //int adpeAccountId = Integer.parseInt(request.getParameter("adpeAccountId"));

        if (request.getParameter("adpeAccountId") == null && request.getAttribute("adpeAccountId") == null) {

            log.debug("rosViewHelper.getAllByAccount() attempted to use 0 as adpeAccountId");
            return null;
        }

        Integer adpeAccountId;
        if (request.getParameter("adpeAccountId") == null) {
            adpeAccountId = (Integer) request.getAttribute("adpeAccountId");
        } else {
            adpeAccountId = new Integer(request.getParameter("adpeAccountId"));
        }

        try {
            List<Ros> results = rosService.getAll(adpeAccountId);
            Collections.sort(results);
            return results;
        } catch (ServiceException e) {
            log.debug("rosViewHelper.getAll(acctId) threw ServiceException", e);
            return null;
        }
    }
}
